package com.atguigu.aiproject.controller.user;

import com.atguigu.aiproject.dto.PublishRequestDTO;
import com.atguigu.aiproject.entity.Result;
import com.atguigu.aiproject.service.CreationLikeService;
import com.atguigu.aiproject.service.CreationService;
import com.atguigu.aiproject.vo.LikeResultVO;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;

@RestController
@CrossOrigin
@RequestMapping("/creation")
public class CreationController {
    private final CreationService creationService;
    private final CreationLikeService creationLikeService;

    public CreationController(CreationService creationService, CreationLikeService creationLikeService) {
        this.creationService = creationService;
        this.creationLikeService = creationLikeService;
    }

    public static class Request {
        public String content;
    }

    // @PostMapping("/test")
    public Result<?> test(
            @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
            @RequestParam(value = "pageSize", defaultValue = "5") int pageSize,
            @RequestBody Request request) {
        return Result.success(creationService.searchCreation(pageNum, pageSize, request.content));
    }

    /**
     * ai搜索文章，用户输入搜索关键字，ai根据搜索关键字生成sql，接口执行sql返回相关文章
     * @param request "查找关于Spring Boot的教程文章，按发布时间倒序排列"
     * @return 搜索结果，不包括文章内容
     */
    @PostMapping("/ai-search")
    public Result<?> search(
            @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
            @RequestParam(value = "pageSize", defaultValue = "5") int pageSize,
            @RequestBody Request request
    ) {
        // TODO 参数校验
        return Result.success(creationService.searchCreation(pageNum, pageSize, request.content));
    }

    /**
     * 翻页请求
     * @param searchId 前端需要保存上一次的查询id，例："a1b2c3d4-e5f6-7890-abcd-ef1234567890"
     * @return 搜索结果，不包括文章内容
     */
    @GetMapping("/ai-list")
    public Result<?> list(
            @RequestParam String searchId,
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "5") int pageSize
    ) {
        return Result.success(creationService.searchCreationByUUid(pageNum, pageSize, searchId));
    }


    /**
     * 发布文章到队列
     * @param publishRequestDTO
     * @param pic 封面
     * @return 只有成功
     */
    @PostMapping("/publish")
    public Result<?> publishToQueue(PublishRequestDTO publishRequestDTO,
                             @RequestParam(value = "pic", required = false) MultipartFile pic) throws IOException {
        creationService.publishToQueue(publishRequestDTO, pic);
        return Result.success();
    }
    /**
     * 点赞文章
     * @param id 文章id
     * @return
     */
    @PutMapping("/like/{id}")
    public Result<LikeResultVO> likeCreation(@PathVariable int id){
        return Result.success(creationLikeService.toggleLike(id));
    }
}

